//
//  TimeWidget.swift
//  WidgetExtension
//
//  Created by Ben on 2022/4/7.
//  Copyright © 2022 Ben. All rights reserved.
//

import WidgetKit
import SwiftUI
import Intents

struct TimeWidgetProvider: IntentTimelineProvider {
  
    
    func getTimeWidgetStyle(for configuration: TimeWidgetIntent) -> TimeWidgetTypeModel {
        if let id = configuration.timeWidgetType?.identifier, let character = UserDefaultGroup.shared.timeWidgetStyle(with: id) {
            // Save the last selected character to our App Group.
            return character
        } else {
            return .normal
        }
    }
    
    func placeholder(in context: Context) -> SimpleEntry {
        SimpleEntry(date: Date(), configuration: TimeWidgetIntent(), widgetTypeModel: .normal)
    }

   
    func getSnapshot(for configuration: TimeWidgetIntent, in context: Context, completion: @escaping (SimpleEntry) -> ()) {
        let entry = SimpleEntry(date: Date(), configuration: configuration, widgetTypeModel: .normal)
        completion(entry)
    }

    
    func getTimeline(for configuration: TimeWidgetIntent, in context: Context, completion: @escaping (Timeline<Entry>) -> ()) {
        
        let typeModel = getTimeWidgetStyle(for: configuration)
        
        var entries: [SimpleEntry] = []

    
        let currentDate = Date()
        for secondOffset in 0 ..< 60 {
            let entryDate = Calendar.current.date(byAdding: .second, value: secondOffset, to: currentDate)!
            let entry = SimpleEntry(date: entryDate, configuration: configuration, widgetTypeModel: typeModel)
            entries.append(entry)
        }
        
        let timeline = Timeline(entries: entries, policy: .atEnd)
        completion(timeline)
    }
}

struct SimpleEntry: TimelineEntry {
    let date: Date
    let configuration: TimeWidgetIntent
    let widgetTypeModel: TimeWidgetTypeModel
    
    var houseAngle: Angle {
        return Angle(degrees: Double(date.getTimeInfo().hour) * (360 / 12) + (Double(date.getTimeInfo().min) / 60 * (360 / 12)))
    }
    
    var minAngle: Angle {
        return Angle(degrees: Double(date.getTimeInfo().min) * (360 / 60))
    }
    
    var secondAngle: Angle {
        return Angle(degrees: Double(date.getTimeInfo().second) * (360 / 60))
    }
}

// 这里就是小组件的UI布局
struct TimeWidgetEntryView : View {
    var entry: TimeWidgetProvider.Entry

    var body: some View {
        
        if entry.widgetTypeModel.type == .electronic {
            ZStack(alignment: .bottomTrailing) {
                Image("widget_clock")
                    .resizable()
                    .aspectRatio(contentMode: .fill)
                
                VStack(spacing: 0) {
                    Text("\(entry.date.hour)")
                    Text("\(entry.date.min)")
                }
                .font(.system(size: 60, weight: .bold))
                .foregroundColor(.white)
            }
        } else {
            ZStack {
                Image("clock_bg")
                    .resizable()
                    .aspectRatio(contentMode: .fill)
                
                if UserDefaultGroup.shared.timeWidgetShowWeek {
                    HStack(spacing: 5) {
                        Spacer()
                        
                        Text("星期")
                            .foregroundColor(.white)
                            .font(.system(size: 10))
                        
                        Text(entry.date.getTimeInfo().week)
                            .font(.system(size: 8, weight: .semibold))
                        .padding(.horizontal, 2)
                        .padding(.vertical, 0)
                        .frame(height: 16)
                        .background(Color.white)
                        
                    }
                    .frame(height: 20)
                    .padding(.trailing, 25)
                }
                
                
                Image("clock_hour")
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                    .rotationEffect(entry.houseAngle)
                
                Image("clock_min")
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                    .rotationEffect(entry.minAngle)
                
                Image("clock_second")
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                    .rotationEffect(entry.secondAngle)

                Image("clock_center")
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                
                
                    
            }
            .padding(14)
        }
        
    }
}

struct TimeWidget: Widget {
    let kind: String = WidgetType.time.kind

    var body: some WidgetConfiguration {
        IntentConfiguration(kind: kind, intent: TimeWidgetIntent.self, provider: TimeWidgetProvider()) { entry in
            TimeWidgetEntryView(entry: entry)
        }
        // 这里定义的就是小组件弹出界面中的标题与副标题
        .configurationDisplayName("桌面时钟")
        .description("通过该组件创建一个桌面小时钟")
        .supportedFamilies([.systemSmall])
    }
}

//struct WidgetExtension_Previews: PreviewProvider {
//    static var previews: some View {
//        WidgetExtensionEntryView(entry: SimpleEntry(date: Date(), configuration: TimeWidgetIntent()))
//            .previewContext(WidgetPreviewContext(family: .systemSmall))
//    }
//}
